<template>
    <div class="date-format-converter">
        <div class="tool-header">
            <h1>英文日期格式转换</h1>
            <p>快速在多种英文日期/时间格式之间互转，支持自定义格式</p>
        </div>

        <el-row :gutter="20">
            <el-col :span="12">
                <el-card>
                    <template #header>
                        <div class="card-header">
                            <span>输入源</span>
                            <div class="actions">
                                <el-button text size="small" @click="setNow">当前时间</el-button>
                                <el-button text size="small" @click="clear">清空</el-button>
                            </div>
                        </div>
                    </template>

                    <el-form label-width="80px" label-position="left">
                        <el-form-item label="原始格式">
                            <el-select v-model="inputFormat" placeholder="选择格式">
                                <el-option v-for="preset in inputFormats" :key="preset.value" :label="preset.label"
                                    :value="preset.value" />
                            </el-select>
                            <el-input v-if="inputFormat === 'custom'" v-model="customInputFormat"
                                placeholder="如：DD/MM/YYYY HH:mm" style="margin-top: 8px;" />
                        </el-form-item>

                        <el-form-item label="输入内容">
                            <el-input v-model="inputValue" type="textarea" :rows="3"
                                placeholder="例如：Tue, 25 Nov 2025 14:30" />
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>

            <el-col :span="12">
                <el-card>
                    <template #header>
                        <div class="card-header">
                            <span>转换结果</span>
                            <el-button type="primary" size="small" @click="convert">转换</el-button>
                        </div>
                    </template>

                    <div v-if="results.length" class="results">
                        <el-table :data="results" border stripe>
                            <el-table-column prop="label" label="格式说明" width="200" />
                            <el-table-column prop="value" label="转换结果">
                                <template #default="{ row }">
                                    <div class="result-row">
                                        <span>{{ row.value }}</span>
                                        <el-button text size="small" @click="copy(row.value)">复制</el-button>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>

                    <el-empty v-else description="输入日期并点击转换，即可看到多种英文格式" />
                </el-card>
            </el-col>
        </el-row>

        <el-card class="info-card">
            <template #header>
                <div class="card-header">
                    <span>格式说明</span>
                </div>
            </template>
            <ul class="info-list">
                <li>默认输出包含公文、博客、简写等常见英文日期格式。</li>
                <li>支持自定义输入格式，格式语法与 dayjs 一致。</li>
                <li>若输入与格式不匹配会提示错误，可使用“当前时间”按钮快速体验。</li>
            </ul>
        </el-card>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'

dayjs.extend(customParseFormat)

const RFC_FORMAT = 'ddd, DD MMM YYYY HH:mm:ss ZZ'

const inputFormats = [
    { label: 'RFC 2822（Tue, 25 Nov 2025 14:30:00 GMT）', value: RFC_FORMAT },
    { label: 'RFC 精简（Tue, 10 Nov 2023 15:30）', value: 'ddd, DD MMM YYYY HH:mm' },
    { label: 'ISO（2025-11-25T14:30:00）', value: 'YYYY-MM-DDTHH:mm:ss' },
    { label: '美式（November 25, 2025 2:30 PM）', value: 'MMMM D, YYYY h:mm A' },
    { label: '英式（25/11/2025 14:30）', value: 'DD/MM/YYYY HH:mm' },
    { label: '自定义格式', value: 'custom' }
]

const outputFormats = [
    { label: '长日期（Tuesday, November 25, 2025）', format: 'dddd, MMMM D, YYYY' },
    { label: '短日期（Nov 25, 2025）', format: 'MMM D, YYYY' },
    { label: '美式时间（Nov 25th, 2025 at 2:30 PM）', format: 'MMM Do, YYYY [at] h:mm A' },
    { label: '英式日期（25 November 2025）', format: 'D MMMM YYYY' },
    { label: '数字日期（25-11-2025）', format: 'DD-MM-YYYY' },
    { label: 'ISO 标准（2025-11-25 14:30:00）', format: 'YYYY-MM-DD HH:mm:ss' },
    { label: 'Unix 时间戳', format: 'X' },
    { label: '相对时间（如 Today at 14:30）', format: '[Today at] HH:mm' }
]

const inputFormat = ref(inputFormats[0].value)
const customInputFormat = ref('')
const inputValue = ref('')
const results = ref([])

const setNow = () => {
    inputValue.value = dayjs().format('ddd, DD MMM YYYY HH:mm:ss ZZ')
    inputFormat.value = 'ddd, DD MMM YYYY HH:mm:ss ZZ'
}

const clear = () => {
    inputValue.value = ''
    results.value = []
}

const getFormat = () => {
    if (inputFormat.value === 'custom') {
        return customInputFormat.value.trim()
    }
    return inputFormat.value
}

const convert = () => {
    const format = getFormat()
    if (!format) {
        ElMessage.warning('请输入自定义格式')
        return
    }
    if (!inputValue.value.trim()) {
        ElMessage.warning('请输入要转换的日期内容')
        return
    }

    const parsed = parseWithFallbacks(inputValue.value.trim(), format)
    if (!parsed.isValid()) {
        ElMessage.error('日期无法解析，请检查输入内容与格式是否一致')
        results.value = []
        return
    }

    results.value = outputFormats.map(item => ({
        label: item.label,
        value: item.format === 'X' ? parsed.unix().toString() : parsed.format(item.format)
    }))
}

const copy = async (text) => {
    try {
        await navigator.clipboard.writeText(text)
        ElMessage.success('已复制')
    } catch (error) {
        ElMessage.error('复制失败')
    }
}

const parseWithFallbacks = (value, baseFormat) => {
    const fallbacks = getFallbackFormats(baseFormat)
    for (const fmt of fallbacks) {
        const parsed = dayjs(value, fmt, true)
        if (parsed.isValid()) {
            return parsed
        }
    }
    return dayjs.invalid()
}

const getFallbackFormats = (format) => {
    if (format === 'custom') {
        return [customInputFormat.value.trim()]
    }

    const map = {
        [RFC_FORMAT]: [
            RFC_FORMAT,
            'ddd, DD MMM YYYY HH:mm:ss',
            'ddd, DD MMM YYYY HH:mm',
            'ddd DD MMM YYYY HH:mm',
            'ddd DD MMM YYYY HH:mm:ss'
        ],
        'ddd, DD MMM YYYY HH:mm': [
            'ddd, DD MMM YYYY HH:mm',
            'ddd DD MMM YYYY HH:mm'
        ],
        'YYYY-MM-DDTHH:mm:ss': [
            'YYYY-MM-DDTHH:mm:ss',
            'YYYY-MM-DD HH:mm:ss',
            'YYYY-MM-DDTHH:mm'
        ],
        'MMMM D, YYYY h:mm A': [
            'MMMM D, YYYY h:mm A',
            'MMM D, YYYY h:mm A'
        ],
        'DD/MM/YYYY HH:mm': [
            'DD/MM/YYYY HH:mm',
            'D/MM/YYYY HH:mm',
            'DD/MM/YYYY'
        ]
    }

    return map[format] ? map[format] : [format]
}
</script>

<style scoped>
.date-format-converter {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.tool-header {
    text-align: center;
    margin-bottom: 30px;
}

.tool-header h1 {
    font-size: 2.2rem;
    margin-bottom: 10px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
}

.actions {
    display: flex;
    gap: 10px;
}

.results {
    max-height: 420px;
    overflow-y: auto;
}

.result-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 10px;
}

.info-card {
    margin-top: 30px;
}

.info-list {
    margin: 0;
    padding-left: 20px;
    color: #666;
    line-height: 1.8;
}
</style>
